#pragma once
#include <iostream>
#include <string>
#include <pthread.h>

class MyThread
{
public:
    typedef enum
    {
        CREATED = 0,
        RUNNING,
        EXITED
    } ThreadStatus;
    typedef void *(*thread_func)(void *);

public:
    MyThread(int num, thread_func func, void *args)
        : _tid(0),
          _status(CREATED),
          _func(func),
          _args(args)
    {
        char name[64];
        snprintf(name, sizeof(name), "Thread_%d", num);
        _name = name;
    }
    int status() { return _status; }
    std::string name() { return _name; }
    pthread_t id() { return _status == RUNNING ? _tid : -1; }

    // static void *runHelper(void *args)
    // {
    //     MyThread *mt = (MyThread *)args;
    //     (*mt)();
    //     return nullptr;
    // }
    // void operator()()
    // {
    //     if (_func != nullptr)
    //         _func(_args);
    // }
    void run()
    {
        // if (0 != pthread_create(&_tid, nullptr, runHelper, this))
        if (0 != pthread_create(&_tid, nullptr, _func, _args))
            exit(-1);
        _status = RUNNING;
    }

    void join()
    {
        if (0 != pthread_join(_tid, nullptr))
        {
            std::cerr << "main thread join thread " << _name << " error" << std::endl;
            exit(-2);
        }
        _status = EXITED;
    }

private:
    pthread_t _tid;
    thread_func _func; // 线程调用的回调函数
    std::string _name;
    void *_args;          // 传给线程的参数
    ThreadStatus _status; // 线程的状态
};